import React from 'react';
import {connect} from 'dva';
import {Table, Row, Col, Form, Input, Icon, InputNumber, Radio, DatePicker, Select, Upload, Button, Switch, Modal, Popconfirm, Tabs, message, Steps} from 'antd';
import RightBox from "../commons/RightBox";
import OperatorConstant from "../../utils/OperatorConstant";
import Statement from '../../components/capital/Statement'
import ApprovalList from '../../components/capital/ApprovalList'
import PayList from '../../components/capital/PayList'
import Detail from '../../components/capital/Detail'
import ForexList from '../../components/capital/ForexList'
import SingleDragger from '../../components/commons/SingleDragger'

const Step = Steps.Step;
const Dragger = Upload.Dragger;
const R = require('ramda');
import moment from 'moment'
import RIGHT from "../../utils/RightConstants";
import Constants from "../../utils/Constants";
import OrderDetail from "../order/components/OrderDetail";
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const dateFormat = 'YYYY-MM-DD';




export default connect(({orderManage})=>({orderManage}))(Form.create({wrappedComponentRef: true})(class CapitalDetail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            disabled: true,
            type: "",
            parOrder: "",
            saveLoading: false,
            submitLoading: false,
        }
    }

    componentWillReceiveProps(nextProps) {
        let dataSource = R.isNil(nextProps.dataSource) || R.isNil(nextProps.dataSource.statement)? {} : nextProps.dataSource.statement;

        if(this.state.open == true){
            let url = R.isNil(this.refs.payOrder) ? "" : this.refs.payOrder.getUrl();
            this.setState({
                parOrder: R.isNil(dataSource.parOrder) ? url : dataSource.parOrder,
            })
        }else{
            this.state.parOrder = "";
            if(this.refs.parOrder)this.refs.parOrder.resetUpload();
        }

    }

    handleResetFields = () => {
        this.props.form.resetFields();
        this.props.dispatch({
            type: 'capital/setApprovalList',
            payload: {
                list: [],
            }
        });

        this.props.dispatch({
            type: 'capital/setPayList',
            payload: {
                list: [],
            }
        });

        this.props.dispatch({
            type: 'capital/setNode',
            payload: {
                node: {},
            }
        });
    }

    handleCancel = () => {
        this.handleResetFields();
        this.setState({open: false});
    }

    handleOpen = (type) => {
        this.state.type = type;
        this.setState({open: true})
    }

    handleConfirm = () => {
        if(this.state.type == OperatorConstant.view){
            return;
        }

        let values = this.props.form.getFieldsValue();

        if(this.state.type == OperatorConstant.capital_pay){
            let url = this.refs.payOrder.getUrl();
            if(R.isNil(url) || R.isEmpty(url)){
                message.error("请先上传付款水单");
                return;
            }
        }

        this.props.form.validateFields((errors, values) => {
            if (errors) return;

            let dataSource = R.isNil(this.props.dataSource) || R.isNil(this.props.dataSource.statement)? {} : this.props.dataSource.statement;
            if(this.state.type == OperatorConstant.approval){
                this.setState({ submitLoading: true });
                this.props.dispatch({
                    type: 'capital/doApproval',
                    payload: {
                        id: dataSource.id,
                        approvalresult: values.approvalresult,
                        approvalmemo: values.approvalmemo,
                        onSuccess: () => this.repetition(),
                        onFail: () => this.setState({submitLoading: false})
                    }
                });

            }else if(this.state.type == OperatorConstant.capital_pay){

                let url = this.refs.payOrder.getUrl();
                let fileName = url.substring(url.lastIndexOf('/') + 1, url.length);
                this.props.dispatch({
                    type: 'capital/doPay',
                    payload: {
                        id: dataSource.id,
                        stateid:  dataSource.id,
                        status: values.status,
                        memo: values.memo,
                        filename: fileName,
                        url: url,
                        onSuccess: () => this.repetition(),
                        onFail: () => this.setState({submitLoading: false})
                    }
                });
            }else if( this.state.type == OperatorConstant.saveAndApproval){

                this.props.dispatch({
                    type: 'capital/updateStatus',
                    payload: {
                        id: dataSource.id,
                        status: "2",
                        onSuccess: () => this.repetition(),
                        onFail: () => this.setState({submitLoading: false})
    
                    }
                });
            }else if( this.state.type == OperatorConstant.capital_pay_approval){

                this.props.dispatch({
                    type: 'capital/updateStatus',
                    payload: {
                        id: dataSource.id,
                        status: "4",
                        onSuccess: () => this.repetition(),
                        onFail: () => this.setState({submitLoading: false})
                    }
                });
            }
        });
    }

    repetition=()=>{
	    this.props.handleSearch();
        this.setState({submitLoading: false});
        this.handleCancel();
   }

    handleCollectForm = () => {
        this.form.payOrder = this.refs.payOrder.getUrl();//this.state.orderso;
        return this.form;
    }

    exportStatement = (id) => {
        this.props.dispatch({
            type: 'capital/exportStatement',
            payload: {
                id: id,
            }
        });
        this.handleCancel();
    }

    onView = (record) => {
        this.handleOpenOrderDetail(record, true, true, true, true, {}, "1");
    }

    handleOpenOrderDetail = (record, orderDisabled, letterDisabled, costDisabled, attachmentDisabled, searchConditions, tabActiveKey) => {
        this.props.dispatch({ type: 'orderManage/getOrderById', payload: { id: record.id } });//获取订单详情
        this.props.dispatch({ type: 'orderManage/queryDrawerList', payload: { cstId: record.cstid } });//查询开票人列表
        this.props.dispatch({ type: 'orderCost/queryOrderCost', payload: { orderId: record.id, status: "2" } });//查询费用列表
        this.props.dispatch({ type: 'orderManage/queryLinkmanList', payload: { cstId: record.cstid } });//查询联系人列表
        this.props.dispatch({ type: 'orderManage/queryAddressList', payload: { cstId: record.cstid } });//查询货物存放地址列表
        this.props.dispatch({ type: 'orderManage/queryBuyerList', payload: { cstId: record.cstid } });//查询境外买家
        this.props.dispatch({ type: 'orderManage/querySupplyGoods', payload: { cstId: record.cstid } });//查询境内货源地
        this.props.dispatch({ type: 'orderManage/queryTgManagers' });//查询通关专员
        this.props.dispatch({type: 'declaration/queryAllLesseeDeclaration'});  //查询市场采购资源-报关抬头
        this.refs.orderDetail.handleOpen(orderDisabled, letterDisabled, costDisabled, attachmentDisabled, searchConditions, tabActiveKey);
    }

    statementMpsColumns = [
        {title: '收款人', dataIndex: 'accname', key: 'accname', width: '100px'},
        {title: '收款人账号', dataIndex: 'accno', key: 'accno', width: '100px'},
        {title: '金额(CNY)', dataIndex: 'amount', key: 'amount', width: '100px'},
        {title: '开户银行', dataIndex: 'accopenbank', key: 'accopenbank'},
        {title: '产生时间', dataIndex: 'createtime', key: 'createtime'},
    ];

    orderColumns = [
        { title: '订单编号', dataIndex: 'orderno', key: 'orderno' },
        { title: '客户名称', dataIndex: 'cstName', key: 'cstName' },
        { title: '合同协议号', dataIndex: 'contractno', key: 'contractno' },
        { title: '报关方式', dataIndex: 'declarationTypeName', key: 'declarationTypeName' },
        { title: '报关口岸', dataIndex: 'portofentryidName', key: 'portofentryidName' },
        { title: '总货值', dataIndex: 'totleamount', key: 'totleamount' },
        { title: '币种', dataIndex: 'currencytype', key: 'currencytype' },
        { title: '提交人', dataIndex: 'creatorName', key: 'creatorName' },
        { title: '提交时间', dataIndex: 'submittime', key: 'submittime' },
        { title: '预计报关时间', dataIndex: 'exporttime', key: 'exporttime' },
        {
            title: '状态', dataIndex: 'status', key: 'status',
            render: (text, record) => {
                return (Constants.ORDERSTATUS[record.status])
            }
        },
        {
            title: '操作', key: 'key_oprator',
            render: (text, record, index) => {
                let viewLink = <a href="#" onClick={this.onView.bind(this, record)}>查看</a>
                return <span>{viewLink}</span>
            }
        }
    ];

    render() {
        let otherFieldValues = this.props.form.getFieldsValue();
        let forexList=R.isNil(this.props.dataSource)?null:this.props.dataSource.forexs;
        let dataSource = R.isNil(this.props.dataSource) || R.isNil(this.props.dataSource.statement)? {} : this.props.dataSource.statement;
        let detail = R.isNil(this.props.dataSource) || R.isNil(this.props.dataSource.detail)? {} : this.props.dataSource.detail;
        let statementMps = R.isNil(this.props.dataSource) || R.isNil(this.props.dataSource.statementMps) ? [] : this.props.dataSource.statementMps;
        let orderList = this.props.dataSource && this.props.dataSource.orderList ? this.props.dataSource.orderList : [];

        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {labelCol: { xs: {span: 8}, sm: {span: 8}}, wrapperCol: {xs: {span: 15}, sm: {span: 14}}};
        let footer = [];

        footer.push(<Button key="cancel" size="large"  onClick={this.handleCancel.bind(this)}>取消</Button>);

        if (this.state.type != OperatorConstant.view) {
            footer.push(<Button key="apply" size="large" loading={this.state.submitLoading} 
            onClick={this.handleConfirm.bind(this)}>确认</Button>);
            //  loading={this.state.submitLoading} disabled={this.state.disabled || this.state.saveLoading|| this.state.type == OperatorConstant.view} 
        }

        // if (!R.isNil(this.props.dataSource.statement) && R.contains(this.props.dataSource.statement.status,["4", "5", "6"])) {
        //     footer.push(<RightBox resource={RIGHT.CUSTOMER.CUSTOMER_DETAIL_PAYAPPLY_EXPORT}><Button key="apply"
        //                                                                                             size="large"
        //                                                                                             onClick={this.exportStatement.bind(this, dataSource.id)}
        //                                                                                            >导出申请书</Button></RightBox>);
        // }


        let node = this.props.capital.node;
        let nodename =""
        let step = "";
        let role =[];
        let isbypass = node.isbypass;
        let approvalDisable = true;



        //当前用户拥有的角色
        if(!R.isNil(node.roles) && !R.isEmpty(node.roles)){
            for(let i=0; i< node.roles.length; i++){
                role.push(node.roles[i].roleId);
            }
        }


        //越级审核
        if(isbypass == 1){
            let approvalRoles =[];

            //审核链角色
            let approvalRole = node.approvalRole;

            let flag = false;
            if(!R.isNil(node.list) && !R.isEmpty(node.list)){
                if(approvalRole == node.list[i].role){
                    flag = true;
                }

                if(flag && R.isNil(node.list[i].role) && R.isEmpty(node.list[i].role) ){
                    approvalRoles.push(node.list[i].role);
                }
            }


            approvalDisable = this.state.type == OperatorConstant.view|| R.isNil(node.approvalRole) || !R.intersection(approvalRoles, approvalRole);


        }else{
            if(!R.isNil(node.list) && !R.isEmpty(node.list) &&  !R.isEmpty(node.roles)){
                let currentNode = 0;

                for(let i=0; i< node.list.length; i++){
                    if(node.nodeName == node.list[i].name){
                        currentNode = i;
                        nodename += "：当前审核节点【" + node.list[i].name + "】";
                        break;
                    }

                }

                for(let i=0; i< node.roles.length; i++){
                    role.push(node.roles[i].roleId);
                }

                step = <Steps current={currentNode} style={{width: '95%'}}>
                    {
                        R.isNil(node.list) || R.isEmpty(node.list)  ? <Step title=""></Step>
                            :
                            node.list.map(item => {
                                return (<Step title={item.name}></Step>);
                            })
                    }
                </Steps>
            }
            approvalDisable =  this.state.type == OperatorConstant.view || R.isNil(node.approvalRole) || !R.contains(node.approvalRole, role);

        }



        let disable = (this.state.type == OperatorConstant.view ? true : false );


        return (
            <Modal maskClosable={false} visible={this.state.open} title={R.isEmpty(step) ? "资金管理" : step } width={1000} wrapClassName="vertical-center-modal"
                   onCancel={this.handleCancel.bind(this)} footer ={footer}>


                <Statement wrappedComponentRef={(inst) => this.statement = inst} dispatch={this.props.dispatch}
                    dataSource={this.props.dataSource} />

                <Tabs  >


                    {/*<TabPane tab="外汇记录" key="1">*/}
                    {/*    <ForexList wrappedComponentRef={(inst) => this.approvalList = inst} dispatch={this.props.dispatch}*/}
                    {/*                  capital={this.props.capital}*/}
                    {/*                  dataSource={dataSource}*/}
                    {/*                    forexs={forexList}*/}

                    {/*    />*/}
                    {/*</TabPane>*/}


                    <TabPane tab="审核记录" key="2">
                        <ApprovalList wrappedComponentRef={(inst) => this.approvalList = inst} dispatch={this.props.dispatch}
                                      capital={this.props.capital}
                                      dataSource={dataSource}/>
                    </TabPane>
                    <TabPane tab="付款记录" key="3">
                        <PayList wrappedComponentRef={(inst) => this.payList = inst} dispatch={this.props.dispatch}
                                 capital={this.props.capital}
                                 dataSource={dataSource}/>
                    </TabPane>
                    <TabPane tab="转账明细" key="4">
                        <Detail wrappedComponentRef={(inst) => this.detail = inst} dispatch={this.props.dispatch}
                                 dataSource={detail}/>
                    </TabPane>
                    {dataSource.businessType === "2" ?
                        <TabPane tab="第二收款人" key="5">
                            <Table dataSource={statementMps} columns={this.statementMpsColumns} bordered={true} size={'middle'} scroll={{ x: true}}/>
                        </TabPane>
                        : ""
                    }

                    {dataSource.settletype === "2" ?
                        <TabPane tab="订单列表" key="6">
                            <Table dataSource={orderList} columns={this.orderColumns} bordered={true} size={'middle'} scroll={{ x: true}}/>
                        </TabPane>
                        : ""
                    }
                </Tabs>


                {this.state.type == OperatorConstant.approval ?
                    <Tabs tabPosition={'top'}>
                        <TabPane tab={"审核" +nodename} key="1">
                            <Form>
                                <Row>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout} label="请选择审核结果" hasFeedback>
                                            {getFieldDecorator('approvalresult', {
                                                rules: [{
                                                    required: true, message: '请选择审核结果！',
                                                }],
                                                initialValue: ''
                                            })(
                                                <Select disabled={approvalDisable}>
                                                    <Option value=""></Option>
                                                    <Option value="2">审核通过</Option>
                                                    <Option value="3">审核不通过</Option>
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={12}>
                                    <FormItem {...formItemLayout} label="备注" hasFeedback>
                                        {getFieldDecorator('approvalmemo', {
                                            rules: [{
                                                required: true, message: '请输入备注！',
                                            }],
                                            initialValue: ''
                                        })(
                                            <Input disabled={approvalDisable} maxLength="100"/>
                                        )}
                                    </FormItem>
                                    </Col>
                                </Row>
                            </Form>
                        </TabPane>
                    </Tabs>
                    : ""}

                {this.state.type == OperatorConstant.capital_pay || this.state.type == OperatorConstant.capital_pay_view ?
                    <Tabs tabPosition={'top'}>
                        <TabPane tab="付款" key="1">
                            <Form>
                                <Row>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout} label="付款结果" hasFeedback>
                                            {getFieldDecorator('status', {
                                                rules: [{
                                                    required: true, message: '请选择付款结果！',
                                                }],
                                                initialValue: ''
                                            })(
                                                <Select disabled={disable}>
                                                    <Option value=""></Option>
                                                    <Option value="1">付款成功</Option>
                                                    <Option value="0">付款失败</Option>
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout} label="付款说明" hasFeedback>
                                            {getFieldDecorator('memo', {
                                                rules: [{
                                                    required: true, message: '付款说明！',
                                                }],
                                                initialValue: ''
                                            })(
                                                <Input disabled={disable}/>
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout}   label={<span className="ant-form-item-required">付款水单</span>} hasFeedback>
                                            <SingleDragger  url={this.state.parOrder}  ref="payOrder" dataSource={this.state.parOrder} disabled={disable}/>
                                        </FormItem>

                                    </Col>
                                </Row>
                            </Form>
                        </TabPane>
                    </Tabs>
                    : ""}

                <OrderDetail ref={"orderDetail"} cstId={dataSource.cstid} {...this.props.orderManage} dispatch={this.props.dispatch} />
            </Modal>
        );
    }
})
)


